<template>
  <div class="app-upload">
    <div class="upload-title">{{ $route.query.type === 'file' ? '上传文件' : '上传文件夹' }}</div>
    <el-upload
      class="upload-demo"
      ref="uploadBox"
      drag
      action="action"
      :before-upload="beforeUpload"
      :http-request="upload"
      :auto-upload="false"
      multiple>
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
    </el-upload>
    <div class="upload-btn">
      <el-button @click="reset">关 闭</el-button>
      <el-button type="primary" @click="sure" :loading="loading">确 定</el-button>
    </div>
  </div>
</template>

<script>
const formData = new FormData()
export default {
  data () {
    return {
      loading: false
    }
  },
  mounted() {
    if (this.$route.query.type === 'folder') { // 上传文件夹
      this.$nextTick(() => {
        document.querySelector('.el-upload__input').webkitdirectory = true
      })
    }
  },
  methods: {
    beforeUpload (file) { // 上传文件之前钩子
      formData.append('files', file)
    },
    upload () {
      this.loading = true
      this.$API({
        name: 'UploadResource',
        data: formData,
        params: {
          path: this.$route.query.path
        },
        requireAuth: true
      }).then (res => {
        if (res.data.code === 200) {
          this.$notify.success(res.data.msg)
        } else {
          this.$notify.error(res.data.msg)
        }
      }).catch(error => {
        this.$notify.error(error)
      }).finally(() => {
        this.loading = false
        this.reset()
      })
    },
    sure () {
      this.$refs.uploadBox.submit()
    },
    reset () {
      this.$router.push({ path: '/info/resource', query: { path: this.$route.query.path } })
    }
  }
}
</script>

<style lang="scss" scoped>
.app-upload {
  padding-top: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  .upload-title {
    padding: 20px 0;
    font-weight: bold;
    color: rgb(78, 78, 78);
  }
  .el-upload-dragger {
    width: 400px !important;
  }
  .upload-btn {
    padding: 20px 0;
  }
}
</style>